<template>
  <div style="text-align: center">

    <el-form ref="regist" :model="regist"   label-width="50px"
             status-icon
             :rules="rules"
             label-position="left"

             class="demo-ruleForm login-page">
      <h3 class="title" style="text-align: center">用户注册</h3>
      <div>
        <el-steps :active="active" simple>
          <el-step :title="item.title" :icon="item.icon" @click.native ="stepClick(item.index)" v-for="item in stepData" :key ="item.index"></el-step>
        </el-steps>
        <br>
        <el-row  class = "active0" v-show="active === 0" >
          <div style="text-align: center;height: 300px">
            <el-form-item label="" prop="username" >
              <el-input v-model="regist.username" style="width: 70%;" >
                <template slot="prepend">用户名</template>
              </el-input>
            </el-form-item>
            <el-form-item label="" prop="password">
              <el-input type="password" v-model="regist.password" style="width: 70%;" >
                <template slot="prepend">密码</template>
              </el-input>
            </el-form-item>
            <el-form-item label="" prop="repassword">
              <el-input type="password" v-model="regist.repassword" style="width: 70%;">
                <template slot="prepend">确认密码</template>
              </el-input>
            </el-form-item>
            <el-form-item label="" prop="phone">
              <el-input v-model.number="regist.phone" style="width: 70%;">
                <template slot="prepend">手机号</template>
              </el-input>

            </el-form-item>
            <el-form-item label="" prop="code">
              <el-input v-model="regist.code" style="width: 70%;">
                <template slot="prepend">验证码</template>
                <el-button slot="append" icon="el-icon-message"
                           :disabled="!show" @click="sendSMS()">
                </el-button>
              </el-input>
              <span v-show="count" style="float: right;margin: 12px 52px 0px -49px ;width: 0px">({{count}}s)</span>

            </el-form-item>
          </div>

          <el-button type="primary" plain size="medium"
                     style="margin-left: 250px"
                     @click="nextClick()">{{nextTile}}

          </el-button>

        </el-row>


        <el-row  class = "active0" v-show="active === 1" >
          <div style="text-align: center;height: 300px">
            <el-form-item label="" prop="sex">
              性别
              <el-radio v-model="regist.sex" label="1">男</el-radio>
              <el-radio v-model="regist.sex" label="0">女</el-radio>
            </el-form-item>

            <el-form-item label="" prop="email">
              <el-input v-model="regist.email" style="width: 70%">
                <template slot="prepend">邮箱</template>
              </el-input>
            </el-form-item>

            <div style="margin: 20px 0;"></div>

            <el-input
                type="textarea"
                :rows="6"
                placeholder="添加个人介绍"
                v-model="regist.aboutme"
                maxlength="30"
                show-word-limit
                style="width: 70%;height: 140px"
            >
            </el-input>

          </div>
          <el-button type="primary" plain size="medium"
                     style="margin-left: 250px"
                     @click="nextClick()">{{nextTile}}
          </el-button>
        </el-row>


        <el-row  class = "active0" v-show="active === 2" >
          <div style="text-align: center;height: 300px">
            <div style="border: dashed 2px;margin: 35px 50px 60px 50px;height: 200px" >

              <el-form-item label="">
                <el-upload ref="upfile"
                           action="#"
                           :auto-upload="false"
                           :on-change="handleChange"
                           :show-file-list="false"
                           :limit="1"
                           accept="image/png,image/gif,image/jpg,image/jpeg"
                >
                  <img v-if="imgUrl" :src="imgUrl" width="180px" height="180px"/>
                  <i v-else class="el-icon-plus" style="font-size: xxx-large;margin-top: 70px"></i>
                </el-upload>
              </el-form-item>

            </div>


            <el-form-item>
              <el-button type="primary"  @click="submitForm('regist')">立即注册</el-button>
              已有账号？
              <el-button type="text"  @click="toLogin">立即登录</el-button>
            </el-form-item>
          </div>
        </el-row>
      </div>
    </el-form>

  </div>

</template>


<script>

export default {
  name: "Register",
  data() {
    var checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('邮箱不能为空'));
      }
      //校验邮箱
      var myreg = /^([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
      setTimeout(() => {
        if (!myreg.test(value)) {
          callback(new Error('请输入正确的邮箱格式'));
        }
        else {
          callback();
        }
      }, 1000);
    };
    var checkUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'));
      }else{
        // axios数据库查询是否有此用户
        this.axios.get('/login/isExist/'+this.regist.username+'').then(res=>{
          if(res.data.code === 0){
            //有该用户，提示错误信息，发送短信按钮不可用
            this.show = false
            callback(new Error("用户名已存在"))
          }else{
            callback();
          }
        })

      }


    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.regist.repassword !== '') {
          this.$refs.regist.validateField('repassword');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.regist.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'));
      }
      //校验手机号
      var myreg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      setTimeout(() => {
        if (!myreg.test(value)) {
          callback(new Error('请输入正确的手机号'));
        }
        else {
          callback();
        }
      }, 1000);
    };
    var code = (rule, value, callback) => {
      let reg = /^\d{6}$/;
      if(!(reg.test(value))) {
        return callback(new Error('请填写6位数字验证码'));
      }else{
        callback();
      }
    };
    return {
      active: 0, // 控制步骤条及填写条目的显示
      stepData: [{index: 0, title: '账号密码', icon: 'el-icon-user'},
        {index: 1, title: '个人信息', icon: 'el-icon-user'},
        {index: 2, title: '个人头像', icon: 'el-icon-user'}],
      nextTile:'下一步',
      show:true, //控制发送验证码的按钮显示
      count:'',

      regist:{

        username:'',
        password:'',
        repassword:'',
        sex:'1',
        email:'',
        phone:'',
        type:1,
        aboutme:'',
        code:'',//验证码
      },

      fileList:[],
      imgUrl:'',

      //规则校验
      rules:{
        // username :[{required: true, message: '请输入', trigger: 'blur'}]
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        repassword: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
        username: [
          { validator: checkUserName, trigger: 'blur' }
        ],
        phone: [
          { validator: checkPhone, trigger: 'blur' }
        ],
        code: [
          { validator: code, trigger: 'blur'}
        ],
      }
    }
  },
  methods: {
    // 步骤条点击事件（因为lement-ui步骤条本身不支持点击事件，所以需要@click.native，来调用原生方法）
    stepClick (val) {
      var _that = this;
      _that.active = val;
    },
    nextClick () {
      var _that= this;
      console.log(_that.active);
      if (_that.active < 3) {
        _that.active ++ ;
        console.log(_that.active);
      } else {
        _that.active = 0;
      }
    },

    //发送验证码
    sendSMS () {
      //校验手机号
      var myreg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if(!myreg.test(this.regist.phone)){
        this.$message.error('请填写正确的手机号');
      }else {
        const TIME_COUNT = 60 //更改倒计时时间

        this.show = false //按钮不可用
        if (!this.timer) {
          this.count = TIME_COUNT;
          this.show = false;
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--;
            } else {
              this.show = true;
              clearInterval(this.timer); // 清除定时器
              this.timer = null;
            }
          }, 1000)
        }

        //发送验证码
        this.axios.post('/register/sendSMS/'+this.regist.phone+'').then(res=>{
          if(res.data.code === 0){
            //console.log(res.data)
            this.$message(res.data.msg)
            this.$message.success('验证码发送成功，请注意查收');
          }else{
            this.$message.error(res.data.data.errMsg)
          }

          console.log(res)
        })


      }


    },


    submitForm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          this.registNow()
        } else {
          // console.log('error submit!!');
          this.$message.error('信息填写有误，请检查');
          return false;
        }
      });


    },

    registNow(){
      var fd = new FormData();
      var face = this.fileList[0];
      // this.fileList.forEach(item=>{
      //     //文件信息中raw才是真的文件
      //     fd.append('files',item.raw);
      //     //console.log(item.raw)
      // })
      // fd.append('file',this.fileList[0].raw)
      fd.append('file',face.raw)
      //console.log(this.fileList[0].raw)
      fd.append('user',JSON.stringify(this.regist) )
      fd.append('code',this.code)
      // console.log(fd.user)
      //this.$axios.defaults.headers.post['Content-Type'] = 'multipart/form-data'
      this.axios.post('/register/uploadAvatar',fd,).then(res=>{
        if(res.data.code === 0){
          //console.log(res.data)
          this.$message(res.data.msg)
          this.$message.success('注册成功')
          this.$refs.regist.resetFields()
          //跳转登录页面
          this.$router.replace({path: '/login'})
        }else{
          this.$message.error(res.data.data.errMsg)
          return
        }

        console.log(res.data.code)
      })
    },


    handleChange(file,fileList){
      const isLt2M = file.size / 1024 / 1024 < 2     //这里做文件大小限制
      if(!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 2MB!',
          type: 'warning'
        });
        this.$refs.upfile.clearFiles();
        return isLt2M
      }else {
        //多次上传
        this.$refs.upfile.clearFiles(); //上传成功之后清除历史记录

        this.fileList = fileList;
        console.log(file)
        //生成本地图片的url，直接src显示,删除或移动后url就失效了
        this.imgUrl = URL.createObjectURL(file.raw);

        console.log(this.imgUrl)
      }

    },
    toLogin(){
      // if(localStorage.getItem('username')){
      //   this.$message('你已登录，请先退出')
      //   return
      // }
      this.$router.replace({path: '/login'})
    },

  }
}
</script>

<style scoped>

</style>